﻿using Newtonsoft.Json;
using System;

namespace Lynn.Infastructure.Utils
{
    public static class JsonNtHelper
    {
        public static JsonSerializerSettings setting { get; private set; }
        static JsonNtHelper()
        {
            setting = new JsonSerializerSettings
            {
                //指定小驼峰
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
                //忽略循环引用
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                //设置时间格式
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            };
        }
        /// <summary>
        /// 将model序列号成json
        /// </summary>
        /// <param name="t">model</param>
        /// <returns></returns>
        public static string ObjectToJson<T>(T t)
        {
            try
            {
                return JsonConvert.SerializeObject(t, setting);
            }
            catch
            {
                return t.ToString();
            }
        }
        /// <summary>
        /// 将json反序列化成model
        /// </summary>
        /// <param name="str">json</param>
        /// <returns></returns>
        public static T JsonToObject<T>(string str)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(str, setting);
            }
            catch
            {
                return default(T);
            }
        }
        public static object JsonToObject(string str, Type t)
        {
            try
            {
                return JsonConvert.DeserializeObject(str, t, setting);
            }
            catch
            {
                return null;
            }
        }
    }
}
